package io.renren.service.impl;

import java.util.Date;

import org.apache.commons.codec.digest.DigestUtils;
import org.beetl.sql.core.engine.PageQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import io.renren.dao.UserDao;
import io.renren.entity.UserEntity;
import io.renren.service.UserService;
import io.renren.utils.RRException;
import io.renren.utils.validator.Assert;



@Service("userService")
public class UserServiceImpl implements UserService {
	@Autowired
	private UserDao userDao;
	
	@Override
	public UserEntity queryObject(Object userId){
		return userDao.unique(userId);
	}
	
	
	@Override
	@Transactional
	public void save(String mobile, String password){
		UserEntity user = new UserEntity();
		user.setMobile(mobile);
		user.setUsername(mobile);
		user.setPassword(DigestUtils.sha256Hex(password));
		user.setCreateTime(new Date());
		userDao.insert(user);
	}
	
	@Override
	@Transactional
	public void update(UserEntity user){
		userDao.updateById(user);
	}
	
	@Override
	@Transactional
	public void delete(Object userId){
		userDao.deleteById(userId);
	}
	
	@Override
	@Transactional
	public void deleteBatch(Object[] userIds){
		for (Object id : userIds) {
			userDao.deleteById(id);
		}
	}

	@Override
	public UserEntity queryByMobile(String mobile) {
		return userDao.queryByMobile(mobile);
	}

	@Override
	public long login(String mobile, String password) {
		UserEntity user = queryByMobile(mobile);
		Assert.isNull(user, "手机号或密码错误");

		//密码错误
		if(!user.getPassword().equals(DigestUtils.sha256Hex(password))){
			throw new RRException("手机号或密码错误");
		}

		return user.getUserId();
	}


	@Override
	public void queryList(PageQuery<UserEntity> query) {
		// TODO Auto-generated method stub
		userDao.queryList(query);
	}


	@Override
	@Transactional
	public void save(UserEntity t) {
		// TODO Auto-generated method stub
		userDao.insert(t);
	}
}
